package com.iflytek.autoCompareTool.service;

import com.iflytek.autoCompareTool.common.Config;
import com.iflytek.autoCompareTool.common.DBManager;
import com.iflytek.autoCompareTool.common.TaskManager;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.sql.SQLException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 监视指定任务是否手动停止
 *
 * @author llchen12
 * @date 2018/6/5
 */
public class Checker {

    private static Logger logger = LoggerFactory.getLogger(Checker.class);


    private ScheduledExecutorService executorService;


    private static Checker instance;

    private Checker() {
        init();
    }

    public static Checker getInstance() {
        if (instance == null) {
            synchronized (Checker.class) {
                if (instance == null) {
                    instance = new Checker();
                }
            }
        }
        return instance;
    }

    public ScheduledExecutorService getExecutorService() {
        return executorService;
    }

    private void init() {
        executorService = new ScheduledThreadPoolExecutor(Config.WORKER_THREAD_CORESIZE,
                new BasicThreadFactory.Builder()
                        .namingPattern("checkProgress-schedule-pool-%d")
                        .daemon(true)
                        .build());
    }


    void check(Integer id) {
        Assert.notNull(id, "要检查的任务id不能为空");
        ScheduledFuture<?> control = executorService.scheduleAtFixedRate(new CheckTask(id),
                0L, Config.CHECKER_FIXRATE_MILLISECONDS, TimeUnit.MILLISECONDS);
        TaskManager.addTaskController(id, control);

    }


    /**
     * 检测任务是否执行完毕或者手动停止
     *
     * @param id 任务id
     * @return 如果progress>=100，返回true
     * *       否则返回false
     */
    private int checkProgress(Integer id) {

        String sql;

        if (id > 0) {
            sql = "select progress from nlu_autotest where id=? ";
        } else {
            sql = "select progress from tool_testupload where id=? ";
        }

        int res;
        try {
            res = DBManager.getInstance().getAiuiManagerQr().query(sql, rs -> rs.next() ? rs.getInt(1) : -1, Math.abs(id));
        } catch (SQLException e) {
            logger.error("查询{}任务进度异常", id, e);
            res = -1;
        }
        return res;
    }


    private class CheckTask implements Runnable {

        private Integer id;

        CheckTask(Integer id) {
            this.id = id;
        }

        @Override
        public void run() {
            logger.debug("启动监视{}号任务", id);
            if (!TaskManager.isCancel(id)) {
                int percent = checkProgress(id);
                System.out.println("--------precent=" + percent);
                if (percent >= 100) {
                    //if (percent == 101) {
                    TaskManager.cancelTask(id);
                    logger.debug("发现" + id + "号任务已被停止，即将退出该任务");
                    //}
                }
            }
        }
    }


}
